package personal.lijun.skeleton.springcloud.gateway;

import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: lijun@sstcsoft.com
 * @Date: 2019/9/25 15:30
 */

@Repository
public class DummyPersonRepository  implements PersonRepository {
    private final Map<Integer, Person> people = new HashMap<>();

    public DummyPersonRepository() {
        this.people.put(1, new Person("John Doe", 42));
        this.people.put(2, new Person("Jane Doe", 36));
    }

    @Override
    public Mono<Person> getPerson(int id) {
        return Mono.justOrEmpty(this.people.get(id));
    }

    @Override
    public Flux<Person> allPeople() {
        return Flux.fromIterable(this.people.values());
    }

    @Override
    public Mono<Void> savePerson(Mono<Person> personMono) {
        System.out.println("savePerson===========================================================");
        System.out.println(Thread.currentThread().getId());
        return personMono.doOnNext(person -> {
            System.out.println("savePerson callback doOnNext===========================================================");
            System.out.println(Thread.currentThread().getId());
            int id = people.size() + 1;
            people.put(id, person);
            System.out.format("Saved %s with id %d%n", person, id);
        }).thenEmpty(Mono.empty());
    }

    public Mono<Void> callUserNext(Mono<User> userMono){
        return userMono.doOnNext(user -> {
            System.out.println("savePerson callback callUserNext===========================================================");
            System.out.println(Thread.currentThread().getId());
        }).thenEmpty(Mono.empty());
    }
}
